<script lang="tsx" setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useElementSize, useFullscreen } from '@vueuse/core';
import { LoadingOutlined } from '@ant-design/icons-vue';

interface Props {
  url: string; // 播放地址
  username: string; // 用户名
  password: string; // 密码
  title?: string; // 标题 如果不传默认使用url
  channel?: string | number; // 通道号 默认1
  subtype: 0 | 1 | 2; // 0：主码流 1：辅码流1 2：辅码流2
}

const props = defineProps<Props>();
const videoRef = ref(null);
const { isFullscreen, exit, toggle } = useFullscreen(videoRef);
const { width } = useElementSize(videoRef);
const loading = ref(false);

const titleFontSize = ref('24px');

watch(
  () => width.value,
  val => {
    titleFontSize.value = `${val / 40}px`;
  },
  {
    immediate: true
  }
);

let player: any;
const canvasElement = ref(null);
const isPlaying = ref(false); // 是否正在播放

const options = {
  wsURL: `ws://${props.url}/rtspoverwebsocket`,
  rtspURL: `rtsp://{props.url}/cam/realmonitor?channel=${props.channel || 1}&subtype=${props.subtype || 0}&proto=Private3`,
  username: props.username,
  password: props.password
};

// 开始播放
function playerPlay() {
  console.log('play');
  loading.value = true;
  player = new window.PlayerControl(options);
  player.on('WorkerReady', function () {
    player.connect();
  });
  player.on('DecodeStart', function (rs) {
    console.log('start decode');
    console.log(rs);
  });
  player.on('PlayStart', function (rs) {
    console.log('play');
    loading.value = false;
    isPlaying.value = true;
    console.log(rs);
  });
  player.on('Error', function (rs) {
    console.log('error');
    console.log(rs);
    if (rs.errorCode === 404) {
      window.$message.error('播放失败，请检查网络或设备是否正常');
    }
  });
  player.init(canvasElement.value);
  window.__player = player;
}

// 停止播放
function playerStop() {
  console.log('stop');
  isPlaying.value = false;
  player.stop();
}

// 关闭播放,断开ws连接
function playerClose() {
  player?.close();
}

// function login(cb: Function) {
//   const target = props.url;
//   setIP(target);
//   RPC.login('admin', 'admin666888', false)
//     .then(res => {
//       setCookie('DWebClientSessionID', '', -1);
//       setCookie('DhWebClientSessionID', '', -1);
//       /** RPC.keepAlive 保活 */
//       _setSession(res.session);
//       RPC.keepAlive(300, 60000, _getSession(), target, 0);
//       cb && cb();
//     })
//     .catch(err => {
//       console.log(err);
//     });
// }

onMounted(() => {
  nextTick(() => {
    playerPlay();
  });
});

onUnmounted(() => {
  playerClose();
});
</script>

<template>
  <div ref="videoRef" class="video h-full w-full">
    <canvas v-show="isPlaying" ref="canvasElement" class="h-full w-full bg-#000"></canvas>
    <div v-show="!isPlaying" class="no-video bg-#000" @click="playerPlay">
      <template v-if="loading">
        <LoadingOutlined />
        <div class="text">视频加载中...</div>
      </template>
      <template v-else>
        <SvgIcon local-icon="play" class="cursor-pointer text-26px" />
        <div class="text">暂无视频</div>
      </template>
    </div>
    <div class="title" :style="{ 'font-size': titleFontSize }">
      {{ props.title || props.url }}
    </div>
    <div class="btn-tools-container">
      <div class="left">
        <span title="播放" @click="playerPlay">
          <SvgIcon v-show="!isPlaying" local-icon="play" class="cursor-pointer text-26px" />
        </span>
        <span title="暂停" @click="playerStop">
          <SvgIcon v-show="isPlaying" local-icon="pause" class="cursor-pointer text-26px" />
        </span>
      </div>
      <div class="right">
        <span v-show="!isFullscreen" title="进入全屏" @click="toggle">
          <SvgIcon local-icon="full-screen" class="cursor-pointer text-26px" />
        </span>
        <span v-show="isFullscreen" title="退出全屏" @click="exit">
          <SvgIcon local-icon="exit-full-screen" class="cursor-pointer text-26px" />
        </span>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.video {
  position: relative;

  .btn-tools-container {
    background-color: rgba(22, 22, 22, 0.8);
    box-sizing: border-box;
    display: flex;
    align-items: center;
    position: absolute;
    justify-content: space-between;
    z-index: 40;
    left: 0;
    right: 0;
    bottom: 0;
    height: 38px;
    width: 100%;
    padding-left: 13px;
    padding-right: 13px;
    font-size: 14px;
    color: #fff;
    user-select: none;
    z-index: 99999;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
  }

  &:hover {
    .btn-tools-container {
      opacity: 1;
    }
  }

  .title {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    text-align: center;
    color: #000;
    font-weight: bold;
    font-size: 24px;
  }

  .no-video {
    color: #fff;
    display: flex;
    height: 100%;
    width: 100%;
    align-items: center;
    justify-content: center;
  }
}
</style>
